package il.ac.technion.wiki.impl.search;

import il.ac.technion.wiki.api.search.Hit;
import il.ac.technion.wiki.api.search.IScorePolicy;
import il.ac.technion.wiki.api.search.IndexSearcher;
import il.ac.technion.wiki.api.search.NeutralWordsCleaner;
import il.ac.technion.wiki.api.wikidocument.IWikiDocument;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class WikiIndexSearcher extends IndexSearcher {
	
	protected List<IWikiDocument> docsLists = new LinkedList<IWikiDocument>();	
	
	public WikiIndexSearcher() {
	}
	
	public WikiIndexSearcher(LinkedList<IWikiDocument> dl, NeutralWordsCleaner c,
			IScorePolicy sp){
		super(dl, c, sp);
	}

	@Override
	public List<Hit> getTermHits(String term) {
		List<Hit> $ = new LinkedList<Hit>();
		ListIterator<IWikiDocument> iter = docsLists.listIterator();
		IWikiDocument currDoc = null;
		while(iter.hasNext()){
			currDoc = iter.next();
			Hit hit = new Hit(scorePolicy.scoreDoc(currDoc, term, cleaner), 
					currDoc.getTitle());
			if (hit.getScore() > 0){
				$.add(hit);
			}
		}
		/*
		Collections.sort($, new Comparator<Hit>() {
			@Override
			public int compare(Hit h1, Hit h2) {
				if (h1.getScore() < h2.getScore())
					return 1;
				if (h1.getScore() > h2.getScore())
					return -1;
				return 0;
			}
		});*/
		//TODO: sort the list
		return $;
	}

	@Override
	public List<Hit> getAllDocsHits() {
		List<Hit> $ = new LinkedList<Hit>();
		ListIterator<IWikiDocument> iter = docsLists.listIterator();
		IWikiDocument currDoc = null;
		while(iter.hasNext()){
			currDoc = iter.next();
			Hit hit = new Hit(1, currDoc.getTitle());
			$.add(hit);
		}
		return $;
	}

	@Override
	public void addDocument(IWikiDocument toAdd) {
		if (toAdd == null)
			throw new IllegalArgumentException("can't add null document");
		docsLists.add(toAdd);
	}

	@Override
	public void removeDocument(IWikiDocument toRemove) {
		if (toRemove == null)
			throw new IllegalArgumentException("can't remove null document");
		docsLists.remove(toRemove);
	}
}